<template>
  <div class="cart_container">
    <div class="cart_content">
      <van-card class="card_overall">
        <template #tags>
          <!-- 商品头部区域 -->
          <div class="overall_header">
            <div class="title">全体换购</div>
            <div class="activity">已满99元,可以选择10件商品换购</div>
            <div class="hydrated">去换购<van-icon name="arrow" /></div>
          </div>
          <!-- 商品滑块区域 -->
          <van-swipe :loop="false" :width="240" :show-indicators="false">
            <van-swipe-item>
              <div class="cards_goods">
                <div class="card">
                  <div class="goods_img">
                    <img src="../../assets/eat.png" alt="" />
                  </div>
                  <div class="goods_info">
                    <div class="goods_title">
                      元气轻食“爱豆”加牛肉，牛与鹰嘴豆 150克
                    </div>
                    <div class="goods_intro">经典五香</div>
                    <div class="goods_price">
                      换购价
                      <span class="price">¥18.6</span>
                      <span class="market_price">￥25</span>
                      <van-icon
                        class="icon_cart"
                        name="shopping-cart-o"
                        size="16"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </van-swipe-item>
            <van-swipe-item>
              <div class="cards_goods">
                <div class="card">
                  <div class="goods_img">
                    <img src="../../assets/eat.png" alt="" />
                  </div>
                  <div class="goods_info">
                    <div class="goods_title">
                      元气轻食“爱豆”加牛肉，牛与鹰嘴豆 150克
                    </div>
                    <div class="goods_intro">经典五香</div>
                    <div class="goods_price">
                      换购价
                      <span class="price">¥18.6</span>
                      <span class="market_price">￥25</span>
                      <van-icon
                        class="icon_cart"
                        name="shopping-cart-o"
                        size="16"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </van-swipe-item>
            <van-swipe-item>3</van-swipe-item>
            <van-swipe-item>4</van-swipe-item>
          </van-swipe>
        </template>
      </van-card>
      <!-- 商品列表 -->
      <div class="goods_list_container" v-show="isShow">
        <div class="goods_list">
          <CartCard v-for="item in shopList" :key="item.id">
            <div class="item_content">
              <van-checkbox
                class="checkout"
                v-model="item.isChecked"
                @click="checkCart(item)"
                checked-color="#ee0a24"
              ></van-checkbox>
              <div class="content_left">
                <img :src="item.imgUrl" />
              </div>
              <div class="content_right">
                <div class="right_title">
                  <div class="red">换购&nbsp;&nbsp;</div>
                  <div class="name">{{ item.skuName }}</div>
                </div>
                <div class="tag">
                  <van-tag
                    round
                    font-size="16px"
                    size="medium"
                    color="#f4f4f4"
                    text-color="#000"
                    >数量:{{ item.skuNum }}</van-tag
                  >
                </div>
                <div class="price_wrap">
                  <div class="price">￥{{ item.cartPrice }}</div>
                  <van-stepper
                    min="1"
                    max="200"
                    @plus="editShopNum(1, item)"
                    @minus="editShopNum(-1, item)"
                    v-model="item.skuNum"
                    disable-input
                    button-size="22"
                  />
                </div>
              </div>
            </div>
            <!-- <div class="info_o">
              <van-icon name="info-o" />不可用劵/红包
              <van-icon name="info-o" />不可用礼品卡
            </div> -->
            <van-swipe-cell>
              <template #left>
                <!-- <van-button square type="primary" text="选择" /> -->
              </template>
              <div class="info_o">
                <van-icon name="info-o" />不可用劵/红包
                <van-icon name="info-o" />不可用礼品卡
              </div>
              <template #right>
                <van-button
                  square
                  type="danger"
                  text="删除"
                  class="delete-button"
                  @click.stop="delGoods(item)"
                />
              </template>
            </van-swipe-cell>
          </CartCard>
        </div>
      </div>

      <!-- 底部 -->
      <div class="h_60"></div>
      <div class="bottom_container">
        <div class="bottom">
          <div class="flex sel_all_wrap">
            <van-checkbox
              v-model="isAllSelected"
              checked-color="#ee0a24"
            ></van-checkbox>
            <span class="sel_all">全选</span>
          </div>
          <div class="middle_content">
            <div class="count">合计：￥{{ goodsAllPrice }}</div>
            <div class="discounts_price">已优惠:￥88,<span>查看详情</span></div>
          </div>
          <div>
            <van-button type="danger" @click="toOrder" class="settle"
              >结算({{ goodsNum }})</van-button
            >
          </div>
        </div>
      </div>
    </div>
    <van-empty
      v-show="!isShow"
      image="https://fastly.jsdelivr.net/npm/@vant/assets/custom-empty-image.png"
      image-size="80"
      description="空空如也，去添加点什么吧！"
      class="empty"
    />
  </div>
</template>

<script lang="ts" setup>
import router from "../../router";
import {
  showLoadingToast,
  closeToast,
  showConfirmDialog,
  showSuccessToast,
  showFailToast,
} from "vant";
import CartCard from "../../components/CartCard/index.vue";
import {
  reqGetShopCart,
  reqEditGoodsNum,
  reqCheckCart,
  reqAllChecked,
  reqDelGoods,
} from "../../api/shopcart";
import {onMounted, ref, computed} from "vue";
import {IShopcartItemParams} from "../../types/cart";
const shopList = ref<IShopcartItemParams[]>([]);
// 判断页面显示与隐藏
const isShow = computed(() => {
  return shopList.value.length > 0;
});
// 获取购物车列表
const getShopList = async () => {
  const result = await reqGetShopCart();
  // console.log(result);
  if (result.data.length) {
    shopList.value = result.data[0].cartInfoList;
  }
};
// 修改商品数量
const editShopNum = (value: number, item: IShopcartItemParams) => {
  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
  });
  return new Promise(async (resolve) => {
    await reqEditGoodsNum(item.skuId, value);
    closeToast();
    // 在 resolve 函数中返回 true 或 false
    resolve(true);
  });
};
// 选中的商品
const checkCart = async (item: IShopcartItemParams) => {
  let {skuId, isChecked} = item;
  let newIsCheck = isChecked ? 1 : 0;
  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
  });
  await reqCheckCart(skuId, newIsCheck);
  closeToast();
};
// 选中商品的数量
const goodsNum = computed(() => {
  return shopList.value.reduce((prev, item) => {
    if (item.isChecked) {
      prev += item.skuNum;
    }
    return prev;
  }, 0);
});
// 选中商品总金额
const goodsAllPrice = computed(() => {
  return shopList.value.reduce((prev, item) => {
    if (item.isChecked) {
      prev += item.skuPrice * item.skuNum;
    }
    return prev;
  }, 0);
});
// 是否全选
const isAllSelected = computed({
  get() {
    return (
      shopList.value.length ===
      shopList.value.filter((item) => item.isChecked).length
    );
  },
  async set(val) {
    const isChecked = val ? 1 : 0;
    const arr = shopList.value.map((item) => item.skuId);
    showLoadingToast({
      message: "加载中...",
      forbidClick: true,
    });
    await reqAllChecked(isChecked, arr);
    closeToast();
    shopList.value.forEach((item) => {
      item.isChecked = isChecked;
    });
  },
});
// 删除商品
const delGoods = async (item: IShopcartItemParams) => {
  showConfirmDialog({
    title: "提示",
    message: "确认要删除吗?",
  })
    .then(async () => {
      const {skuId} = item;
      // console.log(skuId);

      const res = await reqDelGoods(skuId);
      // console.log(res)
      showSuccessToast("删除成功!");
      getShopList();
    })
    .catch((error) => {
      console.log(error);
      showFailToast("删除商品失败");
    });
};
// 提交订单
const toOrder = () => {
  if (goodsNum.value > 0) {
    router.push("/pay");
  }
};
// 挂载
onMounted(() => {
  getShopList();
});
</script>

<script lang="ts">
export default {
  name: "shopcart",
};
</script>

<style lang="scss" scoped>
.h_60 {
  height: 60px;
}
.card_overall {
  background-color: #fff;
  border-radius: 12px;
  margin: 10px;
  padding: 15px;
  .overall_header {
    display: flex;
    justify-content: space-between;
    .title {
      font-weight: 700;
      font-size: 16px;
      color: #333333;
    }
    .activity {
      font-size: 12px;
      color: #333333;
      flex: 1;
      text-align: right;
      margin-right: 8px;
      margin-left: 8px;
    }
    .hydrated {
      font-size: 12px;
      color: #fa1e32;
    }
  }
}
.cart_container {
  height: 100vh;
  .cards_goods {
    margin: 15px 0;
    .card {
      display: flex;
      justify-content: space-between;
      background: #fafafa;
      border-radius: 8px;
      width: 225px;
      height: 70px;
      padding-right: 5px;
      .goods_img {
        width: 70px;
        background: #f4f4f4;
        img {
          display: block;
          width: 70px;
          height: 100%;
        }
      }
      .goods_info {
        height: 70px;
        width: 140px;
        padding: 10px 0;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        .goods_title {
          font-size: 12px;
          color: #333333;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .goods_intro {
          font-size: 10px;
          color: #999999;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          margin-top: 5px;
        }
        .goods_price {
          color: #fa1e32;
          display: inline-block;
          vertical-align: bottom;
          padding-bottom: 12px;
          .price {
            font-size: 20px;
            font-weight: bold;
          }
          .market_price {
            font-size: 12px;
            color: #999;
            text-decoration: line-through;
            font-size: 10px;
            color: #999999;
          }
          .icon_cart {
            margin-left: 10px;
          }
        }
      }
    }
  }
  .goods_list_container {
    .goods_list {
      .item_content {
        margin-top: 10px;
        display: flex;
        .checkout {
          margin-right: 6px;
        }
        .content_left {
          // margin-left: 6px;
          border-radius: 4px;
          overflow: hidden;
          background: #f4f4f4;
          img {
            width: 90px;
            height: 90px;
          }
        }
        .content_right {
          width: 205px;
          flex: 1;
          margin-left: 12px;
          .right_title {
            font-size: 14px;
            height: 21px;
            display: flex;
            .red {
              color: #fa1e32;
              width: 120px;
            }
            .name {
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }
          }
          .price_wrap {
            display: flex;
            margin-top: 10px;
            height: 30px;
            line-height: 20px;
            // justify-content: space-between;
            .price {
              color: #333;
              font-size: 20px;
              font-weight: bold;
            }

            .discounts {
              color: #fa1e32;
              font-size: 14px;
              font-weight: bold;
            }
            .van-stepper {
              display: flex;
              margin-left: 60px;
            }
          }
        }
      }
      .info_o {
        font-size: 12px;
        line-height: 3;
        color: #7f7f7f;
        display: flex;
        align-items: center;
        margin: 10px 0 0 0;
      }
      .delete-button {
        font-size: 12px;
        line-height: 3px;
        padding-bottom: 3px;
        padding-right: 7px;
        // width: 30px;
        height: 20px;
      }
    }
  }
  .bottom_container {
    position: fixed;
    bottom: 50px;
    background-color: #eee;
    width: 100%;
    height: 60px;
    justify-content: center;
    display: flex;
    flex-direction: column;
    .bottom {
      display: flex;
      justify-content: space-around;
      .sel_all_wrap {
        display: flex;
        // justify-content: center;
        align-items: center;
        .sel_all {
          font-size: 16px;
          margin-left: 10px;
        }
      }

      .middle_content {
        font-size: 16px;
        text-align: right;

        .count {
          color: #fa1e32;
          font-family: PingFangSC-Semibold;
        }

        .discounts_price {
          font-size: 13px;
          margin-top: 10px;
          font-family: PingFangSC-Semibold;
        }
      }

      .settle {
        width: 112px;
        height: 36px;
        border-radius: 18px;
      }
    }
  }

  .empty {
    margin-top: 50px;
  }
}
</style>
